import { ipcMain } from 'electron';

// 消息处理器注册表
const handlers = new Map();

export function setupMessageHandlers() {
  ipcMain.on('message', async (event, { uuid, type, data }) => {
    console.log(uuid);
    try {
      // 查找对应的处理器
      const handler = handlers.get(type);
      if (!handler) {
        throw new Error(`Unregistered message type: ${type}`);
      }

      // 执行处理器
      const result = await handler(
        data,
        (replayContent) => {
          event.sender.send(`message-reply-${uuid}`, replayContent);
        },
        ({ destroy } = {}) => {
          if (destroy) {
            console.log('can destroy ' + uuid);

            // 监听 message-destroy-${uuid} 执行 destroy 函数
            ipcMain.on(`message-destroy-${uuid}`, () => {
              destroy();
              ipcMain.removeAllListeners(`message-destroy-${uuid}`);
            });
          }
        }
      );

      // 发送最终结果
      event.sender.send(`message-close-${uuid}`, { data: result });
    } catch (error) {
      // 错误处理
      event.sender.send(`message-close-${uuid}`, {
        error: error.message || 'Message processing failed',
      });
    }
  });
}

export function registerHandler(type, handler) {
  if (typeof handler !== 'function') {
    throw new Error('Handler must be a function');
  }
  handlers.set(type, handler);
}

export function unregisterHandler(type) {
  handlers.delete(type);
}

export function hasHandler(type) {
  return handlers.has(type);
}

export function getRegisteredTypes() {
  return Array.from(handlers.keys());
}
